package cn.hackertools.staticresource.controller;

import cn.hackertools.staticresource.utils.FileHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

@RestController
public class ShareController {

    @Autowired
    private FileHandler fileHandler;
    @Value(value = "${static-resouce-file-path}")
    private String rootPath;
    /**
     * 文件分享
     * @param projectId

     * @return
     */

    @CrossOrigin
    @RequestMapping(value = "/share/{projectId}/**")
    public ModelAndView share(@PathVariable(value = "projectId") String projectId, HttpServletResponse response, HttpServletRequest request){
        ModelAndView modelAndView=new ModelAndView("share/main");
        String requestURI = request.getRequestURI();
        requestURI=requestURI.replace("/share/"+projectId,"");
        String fetch=request.getHeader("Accept");
        System.out.println(fetch);
        System.out.println(requestURI);
        String path=rootPath+ File.separator+projectId+File.separator;
        if(requestURI.indexOf(":")!=-1)
        {
            path+=requestURI.substring(0,requestURI.indexOf(":"));
        }else{
            path+=requestURI;
        }


        System.out.println(path);
        if(path.indexOf(".jsp")!=-1||path.indexOf(".html")!=-1||path.indexOf(".htm")!=-1)
        {
            modelAndView.addObject("data","不可以分享此后缀文件");
            return modelAndView;
        }
        boolean fontFlag=false;
        //处理字体文件
        String[] fontArry=new String[]{"woff2","woff","ttf"};
        for(int i=0;i<fontArry.length;i++)
        {
            if(path.indexOf(fontArry[i])!=-1)
            {
                fontFlag=true;
                response.setContentType("font/"+fontArry[i]);
                try {
                    fileHandler.writeBufForFile(path,response.getOutputStream());
                    response.getOutputStream().flush();
                    response.getOutputStream().close();

                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("data","404找不到文件");
                    return modelAndView;
                }
            }
        }
        boolean imageFlag=false;
        String[] imageArr=new String[]{"png","jpg","jpeg","gif"};
        for(int i=0;i<imageArr.length;i++)
        {
            if(path.indexOf(imageArr[i])!=-1)
            {
                imageFlag=true;
                response.setContentType("image/"+imageArr[i]);
                try {
                    fileHandler.writeBufForFile(path,response.getOutputStream());
                    response.getOutputStream().flush();
                    response.getOutputStream().close();

                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("data","404找不到文件");
                    return modelAndView;
                }
            }
        }
        if(!fontFlag&&!imageFlag)
        {
            try {
                String content = fileHandler.readBody(path);
                if (content == null) {
                    modelAndView.addObject("data", "404找不到文件");
                    return modelAndView;
                }
                if ("*/*".equals(fetch) || fetch.indexOf("text/css") != -1) {
                    //System.out.println(content);
                    ServletOutputStream outputStream = response.getOutputStream();
                    response.setCharacterEncoding("utf-8");
                    outputStream.write(content.getBytes("utf-8"));

                    outputStream.flush();
                    outputStream.close();
                }
                else{
                    modelAndView.addObject("data",content);
                }

            }catch (Exception e)
            {

                e.printStackTrace();
                modelAndView.addObject("data","404找不到文件");
                return modelAndView;
            }
        }

        return modelAndView;

    }
}
